import threading

num = 0
def add(lock:threading.Lock):
    global num
    for _ in range(1000000):
        with lock:
            num+=1


def sub(lock:threading.Lock):
    global num
    for _ in range(1000000):
        with lock:
            num -= 1

if __name__ == '__main__':

    lock = threading.Lock()
    t1 = threading.Thread(target=add,args=(lock,))
    t2 = threading.Thread(target=sub,args=(lock,))

    t1.start()
    t2.start()
    t1.join()
    t2.join()

    # 添加了锁之后 线程安全了
    print(num)